package io.github.echarts.model.series;

import io.github.echarts.model.SeriesModel;
import io.github.echarts.model.context.ConfigurationContext;
import io.github.echarts.option.series.SeriesOption;

import java.util.*;

/**
 * 系列数据分析器
 * <p>
 * 负责对系列数据进行统计分析，提取特征和模式，
 * 为后续的布局和默认配置提供数据支持。
 * </p>
 */
public class SeriesDataAnalyzer {

    /**
     * 对系列数据管理器中的数据进行统计分析
     * 
     * @param seriesManager 系列数据管理器
     * @param context 配置上下文
     */
    public static void analyzeSeriesData(SeriesDataManager seriesManager, ConfigurationContext context) {
        if (seriesManager == null) {
            return;
        }
        
        List<SeriesModel> seriesModels = seriesManager.getSeriesModels();
        if (seriesModels == null || seriesModels.isEmpty()) {
            return;
        }
        
        // 执行各种分析
        analyzeDataDistribution(seriesModels, context);
        analyzeSeriesCorrelation(seriesModels, context);
        analyzeTrends(seriesModels, context);
        detectOutliers(seriesModels, context);
        analyzeStacking(seriesModels, context);
        analyzeDensity(seriesModels, context);
    }
    
    /**
     * 分析数据分布特征
     * 
     * @param seriesModels 系列模型列表
     * @param context 配置上下文
     */
    private static void analyzeDataDistribution(List<SeriesModel> seriesModels, ConfigurationContext context) {
        // 统计值分布情况
        Map<String, Object> distributionStats = new HashMap<>();
        
        // 计算所有系列的值总和
        double sum = 0;
        double min = Double.MAX_VALUE;
        double max = -Double.MAX_VALUE;
        int count = 0;
        
        for (SeriesModel series : seriesModels) {
            List<Object> data = series.getData();
            if (data != null) {
                for (Object item : data) {
                    if (item instanceof Number) {
                        double value = ((Number) item).doubleValue();
                        sum += value;
                        min = Math.min(min, value);
                        max = Math.max(max, value);
                        count++;
                    }
                }
            }
        }
        
        // 计算基本统计数据
        if (count > 0) {
            double average = sum / count;
            distributionStats.put("average", average);
            distributionStats.put("min", min);
            distributionStats.put("max", max);
            distributionStats.put("range", max - min);
            
            // 判断数据分布特征
            boolean mostlyPositive = min >= 0 || (max > 0 && Math.abs(max) > Math.abs(min) * 3);
            boolean mostlyNegative = max <= 0 || (min < 0 && Math.abs(min) > Math.abs(max) * 3);
            boolean centeredAroundZero = !mostlyPositive && !mostlyNegative;
            
            distributionStats.put("mostlyPositive", mostlyPositive);
            distributionStats.put("mostlyNegative", mostlyNegative);
            distributionStats.put("centeredAroundZero", centeredAroundZero);
        }
        
        // 存储到上下文中
        context.addInfo("distributionStats", distributionStats);
    }
    
    /**
     * 分析系列之间的相关性
     * 
     * @param seriesModels 系列模型列表
     * @param context 配置上下文
     */
    private static void analyzeSeriesCorrelation(List<SeriesModel> seriesModels, ConfigurationContext context) {
        if (seriesModels.size() < 2) {
            return;  // 需要至少两个系列才能分析相关性
        }
        
        // 系列间的相关性统计
        Map<String, Object> correlationStats = new HashMap<>();
        
        // 简单判断系列是否有明显的相关性或反相关性
        boolean hasCorrelatedSeries = false;
        boolean hasAntiCorrelatedSeries = false;
        
        // TODO: 实现更复杂的相关性分析，如计算皮尔逊相关系数等
        
        correlationStats.put("hasCorrelatedSeries", hasCorrelatedSeries);
        correlationStats.put("hasAntiCorrelatedSeries", hasAntiCorrelatedSeries);
        
        // 存储到上下文中
        context.addInfo("correlationStats", correlationStats);
    }
    
    /**
     * 分析数据趋势
     * 
     * @param seriesModels 系列模型列表
     * @param context 配置上下文
     */
    private static void analyzeTrends(List<SeriesModel> seriesModels, ConfigurationContext context) {
        Map<String, Object> trendStats = new HashMap<>();
        
        for (int i = 0; i < seriesModels.size(); i++) {
            SeriesModel series = seriesModels.get(i);
            List<Object> data = series.getData();
            
            if (data == null || data.size() < 3) {
                continue;  // 需要至少3个数据点才能分析趋势
            }
            
            // 计算趋势方向
            int increasingCount = 0;
            int decreasingCount = 0;
            
            for (int j = 1; j < data.size(); j++) {
                if (data.get(j) instanceof Number && data.get(j-1) instanceof Number) {
                    double current = ((Number) data.get(j)).doubleValue();
                    double previous = ((Number) data.get(j-1)).doubleValue();
                    
                    if (current > previous) {
                        increasingCount++;
                    } else if (current < previous) {
                        decreasingCount++;
                    }
                }
            }
            
            // 判断系列整体趋势
            String trendDirection = "flat";
            if (increasingCount > decreasingCount * 1.5) {
                trendDirection = "increasing";
            } else if (decreasingCount > increasingCount * 1.5) {
                trendDirection = "decreasing";
            } else if (increasingCount > 0 && decreasingCount > 0) {
                trendDirection = "fluctuating";
            }
            
            // 存储该系列的趋势信息
            trendStats.put("series" + i + "Trend", trendDirection);
        }
        
        // 存储到上下文中
        context.addInfo("trendStats", trendStats);
    }
    
    /**
     * 检测异常值
     * 
     * @param seriesModels 系列模型列表
     * @param context 配置上下文
     */
    private static void detectOutliers(List<SeriesModel> seriesModels, ConfigurationContext context) {
        Map<String, Object> outlierStats = new HashMap<>();
        boolean hasOutliers = false;
        
        for (int i = 0; i < seriesModels.size(); i++) {
            SeriesModel series = seriesModels.get(i);
            List<Object> data = series.getData();
            
            if (data == null || data.size() < 4) {
                continue;  // 需要一定数量的数据才能检测异常值
            }
            
            // 收集数值数据
            List<Double> values = new ArrayList<>();
            for (Object item : data) {
                if (item instanceof Number) {
                    values.add(((Number) item).doubleValue());
                }
            }
            
            if (values.size() < 4) {
                continue;
            }
            
            // 计算四分位距(IQR)来检测异常值
            Collections.sort(values);
            int size = values.size();
            double q1 = values.get(size / 4);
            double q3 = values.get(size * 3 / 4);
            double iqr = q3 - q1;
            double lowerBound = q1 - 1.5 * iqr;
            double upperBound = q3 + 1.5 * iqr;
            
            // 检查异常值
            List<Double> outliers = new ArrayList<>();
            for (Double value : values) {
                if (value < lowerBound || value > upperBound) {
                    outliers.add(value);
                    hasOutliers = true;
                }
            }
            
            // 存储该系列的异常值信息
            if (!outliers.isEmpty()) {
                outlierStats.put("series" + i + "OutliersCount", outliers.size());
                outlierStats.put("series" + i + "OutlierPercentage", (double) outliers.size() / values.size());
            }
        }
        
        outlierStats.put("hasOutliers", hasOutliers);
        
        // 存储到上下文中
        context.addInfo("outlierStats", outlierStats);
    }
    
    /**
     * 分析堆叠系列特征
     * 
     * @param seriesModels 系列模型列表
     * @param context 配置上下文
     */
    private static void analyzeStacking(List<SeriesModel> seriesModels, ConfigurationContext context) {
        Map<String, List<SeriesModel>> stackGroups = new HashMap<>();
        
        // 按堆叠组分类
        for (SeriesModel series : seriesModels) {
            String stack = series.getStack();
            if (stack != null && !stack.isEmpty()) {
                stackGroups.computeIfAbsent(stack, k -> new ArrayList<>()).add(series);
            }
        }
        
        if (stackGroups.isEmpty()) {
            return;  // 没有堆叠系列
        }
        
        Map<String, Object> stackingStats = new HashMap<>();
        stackingStats.put("stackGroupCount", stackGroups.size());
        
        // 分析每个堆叠组
        int maxStackSize = 0;
        for (Map.Entry<String, List<SeriesModel>> entry : stackGroups.entrySet()) {
            int stackSize = entry.getValue().size();
            maxStackSize = Math.max(maxStackSize, stackSize);
            
            // 计算堆叠组的数据总和
            double[] stackSums = calculateStackSums(entry.getValue());
            if (stackSums != null && stackSums.length > 0) {
                double maxSum = Arrays.stream(stackSums).max().orElse(0);
                stackingStats.put("stack_" + entry.getKey() + "_maxSum", maxSum);
            }
        }
        
        stackingStats.put("maxStackSize", maxStackSize);
        
        // 存储到上下文中
        context.addInfo("stackingStats", stackingStats);
    }
    
    /**
     * 计算堆叠系列的数据总和
     * 
     * @param stackSeries 同一堆叠组的系列列表
     * @return 每个数据点的堆叠总和数组
     */
    private static double[] calculateStackSums(List<SeriesModel> stackSeries) {
        if (stackSeries == null || stackSeries.isEmpty()) {
            return null;
        }
        
        // 确定数据点数量
        int dataLength = -1;
        for (SeriesModel series : stackSeries) {
            List<Object> data = series.getData();
            if (data != null) {
                if (dataLength == -1) {
                    dataLength = data.size();
                } else {
                    dataLength = Math.min(dataLength, data.size());
                }
            }
        }
        
        if (dataLength <= 0) {
            return null;
        }
        
        // 计算每个数据点的堆叠总和
        double[] stackSums = new double[dataLength];
        
        for (SeriesModel series : stackSeries) {
            List<Object> data = series.getData();
            if (data != null) {
                for (int i = 0; i < Math.min(dataLength, data.size()); i++) {
                    Object item = data.get(i);
                    if (item instanceof Number) {
                        stackSums[i] += ((Number) item).doubleValue();
                    }
                }
            }
        }
        
        return stackSums;
    }
    
    /**
     * 分析数据密度
     * 
     * @param seriesModels 系列模型列表
     * @param context 配置上下文
     */
    private static void analyzeDensity(List<SeriesModel> seriesModels, ConfigurationContext context) {
        Map<String, Object> densityStats = new HashMap<>();
        
        int totalDataPoints = 0;
        int maxSeriesLength = 0;
        
        for (SeriesModel series : seriesModels) {
            List<Object> data = series.getData();
            if (data != null) {
                totalDataPoints += data.size();
                maxSeriesLength = Math.max(maxSeriesLength, data.size());
            }
        }
        
        // 存储密度信息
        densityStats.put("totalDataPoints", totalDataPoints);
        densityStats.put("maxSeriesLength", maxSeriesLength);
        
        // 判断密度特征
        boolean isHighDensity = totalDataPoints > 100 || maxSeriesLength > 50;
        boolean isLowDensity = totalDataPoints < 10;
        
        densityStats.put("isHighDensity", isHighDensity);
        densityStats.put("isLowDensity", isLowDensity);
        
        // 存储到上下文中
        context.addInfo("densityStats", densityStats);
    }
} 